import {getMenus, logout, modifyPassword} from '../services/common/common';
import {getBusinessParamsByCode} from '../services/basedata/businessParams';
import {getAllCurrencys} from '../services/basedata/currency';
import {getTopTenPorts, getByIds, getListByCodeAndNameAndBusinessType} from '../services/quotationSupport/port';
import {getAreaStreetsTree, getAreaTree} from '../services/basedata/area';
import {getUserInfo, getUsersByRole, updateUser} from '../services/auth/user';
import {queryLesseeOrganizations} from "../services/auth/organization";
import {queryAllRoleList} from "../services/auth/role";
import {browserHistory} from 'dva/router';
import {message} from "antd";
import Constants from '../utils/Constants';

const R = require('ramda');

const paramPreFix = "paramPreFix_";

/**
 * 删除叶子节点children属性
 *
 * @param item
 */
function removeLeafChildren(item) {
    item.key = item.orgId;
    if (item.children.length === 0) {
        delete item.children;
    } else {
        item.children.map(temp => {
            removeLeafChildren(temp);
        });
    }
}
export default {
    namespace: 'app',
    state: {
        isDisplayBreadcrumb: true, // 是否显示面包屑导航
        menus: [], // 菜单
        bizParams: {}, // 业务参数缓存
        currencys: [], // 币种列表
        [Constants.PORTS + Constants.PORT.LOADING]: [], //起运港列表
        [Constants.PORTS + Constants.PORT.DESTINATION]: [], //目的港列表
        port: [], //top10列表
        allPort: [], //港口全部数据
        portSource: [], //根据ids查询的港口数据
        areaTree: [], //省市级联树
        areaStreetTree: [], //街道级联树
        userInfo: {} //右上角修改用户的信息
    },
    reducers: {
        /**
         * 刷新state
         *
         * @param state
         * @param payload
         */
        refreshState(state, { payload }) { return { ...state, ...payload } }
    },
    effects: {
        /**
         * 修改用户
         *
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *updateUser({ payload }, { call, put, select }) {
            const res = yield call(updateUser, { userId: payload.userId, username: payload.username, loginId: payload.loginId, mobile: payload.mobile, email: payload.email, orgIds: payload.orgIds, roleIds: payload.roleIds });
            if (res && res.data.resultCode === "ok") {
                if (payload.onSuccess) payload.onSuccess();
                message.info("修改成功！");
            }
        },

        /**
         * 获取当前登录用户菜单集合
         *
         * @param appCode
         * @param pathname
         * @param call
         * @param put
         * @param select
         */
        *getMenus({ pathname }, { call, put, select }) {
            const res = yield call(getMenus);
            if (res && res.data.resultCode === 'ok') {
                let menus = res.data.content;
                yield put({ type: 'refreshState', payload: { menus } });
            }
        },
        /**
         * 退出登录
         *
         * @param call
         * @param put
         */
        *logout({ }, { call, put }) {
            yield call(logout);
            sessionStorage.clear();
            browserHistory.push("/login");
        },
        /**
         * 获取业务参数集合
         *
         * @param call
         * @param put
         * @param select
         */
        *getBusinessParamsByCode({ sprCode }, { call, put, select }) {
            const sessionSprCode = sessionStorage.getItem(paramPreFix + sprCode);
            let bizParams = yield select(state => state.app.bizParams);
            if (R.isNil(sessionSprCode)) {
                const res = yield call(getBusinessParamsByCode, { sprCode });
                if (res && res.data.resultCode === 'ok') {
                    sessionStorage.setItem(paramPreFix + sprCode, JSON.stringify(res.data.content));
                    bizParams[sprCode] = res.data.content;
                    yield put({ type: 'refreshState', payload: { bizParams } });
                }
            } else {
                bizParams[sprCode] = JSON.parse(sessionSprCode);
                yield put({ type: 'refreshState', payload: { bizParams } });
            }
        },
        /**
         * 获取所有币种
         *
         * @param call
         * @param put
         */
        *getAllCurrencys({ }, { call, put, select }) {
            const sessionCurrency = sessionStorage.getItem(Constants.preCurrency);
            if (R.isNil(sessionCurrency)) {
                const res = yield call(getAllCurrencys);
                if (res.data.resultCode === 'ok') {
                    sessionStorage.setItem(Constants.preCurrency, JSON.stringify(res.data.content));
                    yield put({ type: 'refreshState', payload: { currencys: res.data.content } });
                }
            } else {
                yield put({ type: 'refreshState', payload: { currencys: JSON.parse(sessionCurrency) } });
            }
        },
        /**
         * 港口top10下拉列表
         *
         * @param call
         * @param put
         */
        *getTopTenPorts({ payload }, { call, put, select }) {
            const res = yield call(getTopTenPorts, { ...R.omit(['onFail'])(payload) });
            if (res.data.resultCode === 'ok') {
                let data = res.data.content.list;
                yield put({
                    type: 'refreshState',
                    payload: {
                        port: data
                    }
                });
                if (payload.onSuccess) payload.onSuccess(data);
            } else {
                yield put({ type: 'refreshState', payload: { port: [] } });
            }
        },
        /**
         * 查找港口全部数据
         *
         * @param call
         * @param put
         */
        *getListByCodeAndNameAndBusinessType({ payload }, { call, put, select }) {
            const res = yield call(getListByCodeAndNameAndBusinessType, { ...R.omit(['onSuccess', 'onFail'])(payload) });
            if (res.data.resultCode === 'ok') {
                let source = res.data.content.list;
                if (payload.onSuccess) payload.onSuccess(source);
            } else {
                yield put({ type: 'refreshState', payload: { port: [] } });
            }
        },
        /**
         * 根据ids获取港口
         *
         * @param ids
         * @return
         */
        *getByIds({ payload }, { call, put }) {
            const res = yield call(getByIds, { ...R.omit(['onSuccess', 'onFail'])(payload) });
            if (res && res.data.resultCode === 'ok') {
                let portSource = res.data.content;
                if (payload.onSuccess) payload.onSuccess(portSource)
            } else {
                if (payload.onFail) payload.onFail();
            }
        },
        /**
         * 获取省市区级联树
         *
         * @param call
         * @param put
         */
        *getAreaTree({ onSuccess }, { call, put, select }) {
            const res = yield call(getAreaTree, );
            if (res.data.resultCode === 'ok') {
                let data = res.data.content;
                if (onSuccess) onSuccess(data);
            }
        },
        /**
         * 获取街道级联树
         *
         * @param call
         * @param put
         */
        *getAreaStreetsTree({ districtCode, onSuccess }, { call, put, select }) {
            const res = yield call(getAreaStreetsTree, { districtCode });
            if (res.data.resultCode === 'ok') {
                let data = res.data.content;
                let streets = [];
                (data ? data : []).map((row) => {
                    streets.push({ label: row.streetsName, value: row.streetsCode })
                })
                if (onSuccess) { onSuccess(streets) }

            }
        },

        /**
         * 修改密码
         *
         * @param call
         * @param put
         */
        *modifyPassword({ payload }, { call, put, select }) {
            const res = yield call(modifyPassword, { oldPwd: payload.oldPassword, newPwd: payload.loginPwd });
            if (res && res.data.resultCode === 'ok') {
                message.info("密码修改成功，下次登录登陆生效");
                if (payload.onSuccess) { payload.onSuccess() }
            } else {
                if (payload.onFail) payload.onFail();
            }
        },

        /***
         * 获取当前用户
         * @param payload
         * @param call
         * @param select
         * @param put
         */
        *getUserInfo({ payload }, { call, select, put }) {
            const res = yield call(getUserInfo);
            const organization = yield call(queryLesseeOrganizations);
            const roles = yield call(queryAllRoleList);
            if (res.data.resultCode == "ok" && organization.data.resultCode == "ok" && roles.data.resultCode == "ok") {
                let content = res.data.content;
                let rolesContent = roles.data.content;
                let orgContent = organization.data.content;
                orgContent = orgContent.map(item => {
                    removeLeafChildren(item);
                    return item;
                });

                let userInfo = { ...content };
                userInfo.orgIds = (content.orgIds ? content.orgIds : []).map((item) => {return item + ""});
                userInfo.roleIds = (content.roles ? content.roles : []).map((item) => {return item.roleId + ""});
                userInfo.roles = rolesContent ? rolesContent : [];
                userInfo.organization = orgContent ? orgContent : [];
                yield put({ type: 'refreshState', payload: { userInfo } })
            }
        },

        /**
         * 根据角色获取用户
         * @param payload
         * @param call
         * @param select
         * @param put
         */
        *getUsersByRole({ payload }, { call, select, put }) {
            const users = sessionStorage.getItem(payload.role);
            if (users) {
                yield put({ type: 'refreshState', payload: { [payload.role]: JSON.parse(users) } });
            } else {
                const res = yield call(getUsersByRole, payload);
                if (res && res.data.resultCode === 'ok') {
                    sessionStorage.setItem(payload.role, JSON.stringify(res.data.content));
                    yield put({ type: 'refreshState', payload: { [payload.role]: res.data.content } });
                }
            }
        },

    },
    subscriptions: {
        setup({ history, dispatch }) {
            return history.listen(({ pathname }) => {
                if (pathname.includes('/logout')) {
                    dispatch({ type: 'logout' });
                } else {
                    if (!pathname.includes('login')) {
                        dispatch({ type: 'getMenus', pathname });
                    }
                }
            });
        }
    }
};